<template>
  <div style="height: 100vh;">
     <div style="display: flex;height: 100%;" v-loading='loading'>
       <el-drawer
         title="请选择用户"
         :visible.sync="drawer"
         :before-close="handleClose"
         direction="rtl">
         <div style="padding: 15px;">
           <el-select v-model="constructInfo[0].uids" multiple filterable placeholder="请选择">
               <el-option
                 v-for="(item, index) in userList"
                 :key="index"
                 :label="item.nickName"
                 :value="item.userId">
               </el-option>
             </el-select>
         </div>
       </el-drawer>
       <div class="constructList" style="border-right: 1px solid #eee;padding: 0 15px;position: relative;height: 80%;min-width: 300px;">
         <el-button type="primary" @click="openDrawer">选择接收用户</el-button>
         <el-input
           style="width: 50%;"
           placeholder="输入关键字进行过滤"
           v-model="filterText">
         </el-input>
           <div style="height: 85%;overflow: auto;min-width: 30%;" class="scroll">
             <el-tree
                  @node-click='currentChange'
                  style="margin-top: 20px;"
                  :data="constructInfo"
                  node-key="id"
                  :default-checked-keys='[21]'
                  :highlight-current='true'
                  ref="tree"
                  default-expand-all
                  :filter-node-method="filterNode"
                  :expand-on-click-node="false">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ data.isTask?data.taskName:data.titleName}}</span>
                    <span style="float: right;">
                      <el-popover
                      v-throttle
                         placement="top-start"
                         title=""
                         trigger="hover"
                         content="点击添加子节点">
                         <i
                           v-if="!data.isTask"
                           slot="reference"
                           class="el-icon-circle-plus-outline"
                           style="font-size: 24px;"
                           @click="() => append(data)">
                         </i>
                       </el-popover>
                       <el-popover
                          placement="top-start"
                          title=""
                          trigger="hover"
                          v-if="!data.isFirst"
                          content="点击移除该任务">
                          <i
                            slot="reference"
                            style="font-size: 24px;"
                            class="el-icon-remove-outline"
                            @click="() => remove(node, data)">
                          </i>
                        </el-popover>
                    </span>
                  </span>
                </el-tree>
           </div>
            <el-button type="primary" @click="publish" style="" v-if="!isEdit">发布项目</el-button>
       </div>
       <div class="missionDetail" style="padding: 0px 40px;box-sizing: border-box;" v-if="handleTreeNode">
          <el-form :model="handleTreeNode" status-icon  ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <!-- <el-form-item label="项目名称" prop="checkName" v-if="handleTreeNode.isFirst">
              <el-input @change="edited=true" v-model="handleTreeNode.titleName" placeholder="请输入指标名称" autocomplete="off"></el-input>
            </el-form-item> -->
            <el-form-item label="指标名称" prop="checkName" v-if="!handleTreeNode.isTask&&!handleTreeNode.isFirst">
              <el-input @change="edited=true" v-model="handleTreeNode.titleName" placeholder="请输入指标名称" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="任务名称" prop="checkName" v-if="handleTreeNode.isTask&&!handleTreeNode.isFirst">
              <el-input @change="edited=true" v-model="handleTreeNode.taskName" placeholder="请输入任务名称" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="目标值" prop="checkTarget" v-if="handleTreeNode.isTask&&!handleTreeNode.isFirst">
              <el-input @change="edited=true" v-model="handleTreeNode.target" autocomplete="off" placeholder="请输入目标值"></el-input>
            </el-form-item>
            <el-form-item label="节点类型" v-if="!handleTreeNode.isFirst">
              <el-radio-group v-model="handleTreeNode.isTask" @input="nodeInput">
                    <el-radio :label="0">指标</el-radio>
                    <el-radio :label="1">任务</el-radio>
                  </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="edit" v-if="this.isEdit">保存修改</el-button>
            </el-form-item>
          </el-form>
       </div>
     </div>
     <div ref="pdf">

     </div>
  </div>
</template>

<script>
  export default{
    name: "teamproject",
    data(){
      let checkTarget=(rule, value, callback)=>{
        if(value=='') callback(new Error('请输入目标值'))
      }
      return{
        constructInfo:[
          {
            titleName:'任务清单',//项目名称
            isTask:0,
            isFirst:false,
            uids:[],
            children:[]
          }
        ],
        filterText:'',
        handleTreeNode:null,
        loading:false,
        drawer:false,
        userList:[],
        isEdit:false,
        editNode:null,
        edited:false,
        querys:this.$route.query
      }
    },
    methods:{
      append(data) {
        const newChild = {titleName: '请填写指标', children: [],isTask:0,taskName:'请填写任务',target:''};
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
        this.handleTreeNode=data.children[data.children.length-1]
        console.log(data.children[data.children.length-1])
      },
      remove(node, data) {
        this.$confirm('是否删除当前节点？删除该节点后该节点下的子节点也将被删除！','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex(d => d.id === data.id);
          children.splice(index, 1);
        })
      },
      nodeInput(label){
        this.handleTreeNode.isTask=0
        this.edited=true
        if(label==1){
          this.$confirm('当前节点类型设置为任务会将该节点下子节点移除，是否继续？','提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(()=>{
            this.handleTreeNode.isTask=1
            this.handleTreeNode.titleName=''
            this.handleTreeNode.children=[]
          }).catch(()=>{
            this.handleTreeNode.isTask=0
          })
        }else{
          this.handleTreeNode.taskName=''
          this.handleTreeNode.target=''
        }
      },
     publish(){
      if(this.constructInfo[0].uids.length==0) return this.$message.warning('请选择接收用户')
      this.$confirm('确认发布改项目','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async ()=>{
        this.loading=true
        let result =await this.$post('/api/add/construct',this.constructInfo[0])
        if(result.code==200){
          this.loading=false
          this.$message.success('发布成功')
          this.$router.back()
        }else {
          this.$message.error(result.msg)
          this.loading=false
        }
      })
    },
    openDrawer(){
      this.drawer=true
      this.$get('/api/users/list').then(res=>this.userList=res.data)
    },
    filterNode(value, data) {
      if (!value) return true;
      let key=data.titleName==''?'taskName':'titleName'
      return data[key].indexOf(value) !== -1;
    },
    handleClose(done) {
           this.$confirm('是否保存当前选择的用户？')
             .then(_ => {
               done();
             })
             .catch(_ => {
               this.constructInfo[0].uids=[]
               done();
             });
     },
     async edit(){
       let children=undefined
       if(this.handleTreeNode.children){
         children=this.handleTreeNode.children
         this.handleTreeNode.children=undefined
       }
       this.loading=true
      let result =await this.$post('/api/add/construct',this.handleTreeNode)
      if(result.code==200){
        Object.assign(this.editNode,this.handleTreeNode)
        this.editNode.children=children?children:undefined
        this.loading=false
        this.edited=false
        this.$message.success('修改成功')
        return new Promise((resolve)=>{
          resolve()
        })
      }
     },
     currentChange(obj){
       if(this.edited){
         this.$confirm('是否保存当前修改?', '提示', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
         }).then(() => {
          this.edit().then(()=>{
            this.handleTreeNode=JSON.parse(JSON.stringify(obj))
            this.editNode=obj
          })
         }).catch(()=>{
           this.handleTreeNode=JSON.parse(JSON.stringify(obj))
           this.editNode=obj
         })
       }else {
         this.handleTreeNode=JSON.parse(JSON.stringify(obj))
         this.editNode=obj
       }
       this.edited=false
     },
    init(){
      if(this.$route.query.id){
        this.loading=true
        this.isEdit=true
        this.$get('/api/getConstruct/'+this.$route.query.id).then(res=>{
          this.loading=false
          this.constructInfo=[]
          res.data['uids']=[]
          this.constructInfo.push(res.data)
          this.editNode=this.constructInfo[0]
          this.handleTreeNode=this.constructInfo[0]
        })
      }
      // this.$store.commit('removeAnalogueTab',"/home/teamproject")
      this.$nextTick(()=>{
          // console.log(this.$route.query.id,typeof this.$route.query.id)
          if(parseInt(this.$route.query.id)==0||this.$route.query.id=='undefined'||this.$route.query.id==undefined){
            // this.$store.commit('removeAnalogueTab',"/home/teamproject")
            // this.$store.commit('setTabs',{
            //   name: "/home/teamproject",
            //   title: "建设项目"
            // })
          }else{
            // this.$store.commit('setTabs',{
            //   name: "/home/teamproject?id="+this.$route.query.id,
            //   title: "建设项目"
            // })
          }
      })
    }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      querys(val){
        console.log('change..')
        this.init()
      }
    },
    created(){
      this.init()
    }
  }
</script>

<style scoped lang="scss">
  /deep/ .custom-tree-node{
    width: 100%;
    display: flex;
    justify-content: space-between;
    white-space: nowrap;
  }
  /deep/ .el-tree-node__content{

  }

  .scroll {
      overflow: auto;
     }

     .scroll::-webkit-scrollbar {
      width: 4px;
      height: 4px;
     }

     .scroll::-webkit-scrollbar-thumb {
      border-radius: 10px;
      background: #444;
     }

     .scroll::-webkit-scrollbar-track {
      border-radius: 0;
      background-color: rgba(0 ,0 , 0 , .1 );
     }
</style>
